#! /usr/bin/perl

#use the HMTLSubs package and ValidationSubs package as well as the database
use HTMLSubs;
use ValidationSubs;
use DBQueries;
use CGI;

#also enable strict mode
use strict;

#start by determining if any information was passed to the script so that the proper actions can be taken
#obtain the input 
my $input = obtain_input();

#ensure that input is not blank which would mean that the site is illegally accessed
if(length($input) == 0){
	
	#if so, redirect to login
	print CGI -> redirect("login.pl.cgi");
}

#call method to split the full string into a hash of individual variables
#this subroutine returns a reference to the submitted info hash
my $ref_submitted_info = HTMLSubs->decode_input($input);

#dereference the submitted info
my %submitted_info = %$ref_submitted_info;

#declare username to hold owner of the files
my $username;
# isolate the username and proceed
$username = $submitted_info{'username'};

#if the only input is username i.e. the size is 1, 
if(scalar(keys %submitted_info) == 1){
	
	#now call the subroutine to display the group submission form
	display_search($ENV{'SCRIPT_NAME'});
}

#otherwise we know that a keyword was entered so act accordingly
else{
	
	#now call subroutine to process input
	#pass this sub the keyword to be searched
	#this subroutine will take control of the flow of the script and determine what actions to further take
	process_search($submitted_info{'keyword'});
}

#subroutine to display the initial search site
sub display_search{
	
	#obtain target and potential errors from parameters
	my $form_target = $_[0];
	my $error_text = $_[1];
	
	#call the necessary html subs to print headers
	#call method to display html beginnign
	HTMLSubs->generate_html_beginning("Search your files");
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "Search Document Content", $username);
	
	#now display the actual search field
	print <<END_HTML;
	<div class="content">
END_HTML

	#print any potential error messages passed to the subroutine and ensure that not too many <br> tags are printed
	#by determining if the length of the text is 0 or not
	if(length($error_text) != 0){
		print "<p>$error_text</p>";
	}
	#print actual form
	print <<END_HTML;
	<table>
			<form action="$form_target" method=POST>
			<tr>
				<!-- group name-->
				<td><p>Keyword:*</p></td>
				<td><input type="text" name="keyword"></td>
				
				<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
				<input type="hidden" name="username" value="$username">
			</tr>
			<tr>
				<!--submit button-->
				<td><input type="submit" value="Submit"></form>
END_HTML

	#create cancel button
	#create parameter hash
	my %parameter_hash;
	$parameter_hash{'username'} = $username;
		
	#call subroutine to crate a cancel button
	#this button will link back to profile
	HTMLSubs -> generate_html_button("profile.pl.cgi", "Cancel", \%parameter_hash);
		
		#print remaining tags
		print <<END_HTML;
			</td>
		</tr>
	</table
END_HTML
	
}

#subroutine to process the search for specific keywords
sub process_search{
	
	#obtain keyword from parameter
	my $keyword = $_[0];
	
	#ensure that keyword was not blank
	if(length($keyword) == 0){
		
		#show error and return to search page
		my $error_text = "<h4><font color=\"red\">You left the field blank.<br>Please try again.</font></h4>";
		display_search($error_text);
	}
	#otherwise proceed with search
	else{
		
		#now display this accordingly
		display_matches($keyword);
	}
}

#subroutine to display all matching files of a specific keyword
sub display_matches{
	
	#get keyword form parameter
	my $keyword = $_[0];

	#obtain list of matching files from database
	my @matching_files = DBQueries::getInfoTypeValueConstraint($username, "keyword", $keyword, ">", 0) ;
	
	
	#print header
	HTMLSubs -> generate_html_beginning("Your Search Results");
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "The results of search for $keyword", $username);
	
	#now proceed to display them accordingly
	#print remaining html code
	print <<END_HTML;
	<!--now proceed to main body-->
	<div class="content">
	<table class="tablecontent">
	<tr class="trmain">
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--group information-->
	<h4>Files whose content matches $keyword</h4>
	<table>
		
		<tr>
		<!--scroll list for appropriate files-->
		<td>
END_HTML

	#make sure that there are files
	if($matching_files[0] ne "0"){
		print <<END_HTML;
		<p>
		<form action="profile.pl.cgi" method=POST>
		<select name="fileSelected" size="10">
END_HTML

		#now loop through list to display all files
		#now print the remaining file names in teh array except for the potentially selected file
		#declare temp scalar to help with loop
		my $current_file;
		my $current_name;
	
		#now loop through array
		foreach $current_file(@matching_files){
			
			$current_name = DBQueries::getFileName($current_file);
			print "<OPTION>$current_name";
		}
		
		#now proceed to print the html to finish the file list and selection
		print <<END_HTML;
	
		</select>
		<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
		<input type="hidden" name="username" value="$username">
		
		<!-- now create a hidden field that resubmits the groupname so that the script knows what group is currently selected-->
		<input type="hidden" name="groupSelected" value="">
		
		</p>
		
		<!--submit button-->
		<p><input type="submit" value="View File Information"></form></p></td></tr>
END_HTML
	}
	else{
		print"<p>There are no files whose content matches the keyword.</p></td></tr>";
	}
	
	
	#print remainder of tags
	print <<END_HTML;
	</div>
	</td>
	</tr>
	</table>
	</div><!--content-->
END_HTML

	#call sub to print the footer
	HTMLSubs -> generate_html_end();
}

#subroutine to obtain and determine what information is passed to the script
#to make this more universal, both GET and POST methods are accepted 
#this reads input for both GET and POST
sub obtain_input{

	#declare scalar to hold passed information
	my $input;

	#now retrieve the input through either get or post
	#change the case of request method
	$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

	#if post use STDIN
	if ($ENV{'REQUEST_METHOD'} eq "POST"){
		read(STDIN, $input, $ENV{'CONTENT_LENGTH'});

		#exchange plus signs to spaces
		$input =~ s/\+/ /;

		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	#otherwise the env hash
	else{
		$input = $ENV{'QUERY_STRING'};
		
		#exchange plus signs to spaces
		$input =~ s/\+/ /;
		
		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	
	#now return the correct input
	return $input;	
}
